package com.sz.biz.csr.service.impl;

import com.sz.biz.csr.entity.CsrAskBoardDetail;
import com.sz.biz.csr.entity.CsrAskBoardSchema;
import com.sz.biz.csr.dto.CsrAskBoardDetailDto;
import com.sz.biz.csr.service.CsrAskBoardDetailService;
import com.sz.biz.common.constants.ErrorCodes;
import com.sz.biz.common.constants.ModuleNames;
import com.sz.biz.common.customer.entity.CusUser;
import com.sz.biz.common.customer.service.CustomerUserService;
import com.sz.common.base.constants.AppDomain;
import com.sz.common.base.constants.UserActions;
import com.sz.common.base.dao.ParamData;
import com.sz.common.base.dto.QResultDto;
import com.sz.common.base.dto.QueryParams;
import com.sz.common.base.exception.Exceptions;
import com.sz.common.base.service.AbstractService;
import com.sz.common.base.utils.StringUtils;
import com.sz.common.core.service.PrincipalLogUtils;
import com.sz.common.core.service.PrincipalUtils;
import com.sz.common.core.system.dto.FileInfoDto;
import com.sz.common.core.system.entity.SysFile;
import com.sz.common.core.system.service.SysFileGroupService;
import com.sz.common.core.system.service.SysFileService;
import com.sz.common.core.system.dto.UserDto;
import com.sz.common.core.system.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by xutao on 17/5/15.
 */
@Service("CsrAskBoardDetailService")
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public class CsrAskBoardDetailServiceImpl extends AbstractService implements CsrAskBoardDetailService {

    @Autowired
    CustomerUserService customerUserService;

    @Autowired
    UserService userService;

    @Autowired
    SysFileGroupService fileGroupService;

    @Autowired
    private SysFileService sysFileService;

    @Override
    public CsrAskBoardDetailDto save(CsrAskBoardDetail entry) {

        int resId = 0;

        if (entry != null) {

            checkDataValid(entry);

            CsrAskBoardSchema csrAskBoardSchema = (CsrAskBoardSchema) dao.findForObject(getSqlName("selectByAskBoardId"), entry.getRefAskBoardId());

            if (csrAskBoardSchema != null) {

                if (PrincipalUtils.getAccountId() != csrAskBoardSchema.getRefCustomerId()) {

                    entry.setIsModerator(false);
                } else {

                    entry.setIsModerator(true);
                }

                entry.setRefReplyerId(PrincipalUtils.getAccountId());

            }

            dao.save(getSqlName("insertSelective"), entry);

            CsrAskBoardSchema updatedSchema = new CsrAskBoardSchema();

            updatedSchema.setId(entry.getRefAskBoardId());
            updatedSchema.setLastReplyId(entry.getRefReplyerId());
            updatedSchema.setContent(entry.getMessageBody());
            updatedSchema.setModeratorForReplyer(entry.getIsModerator());
            updatedSchema.setUpdateTime(dao.getDbDate());

            if (PrincipalUtils.getDomainId() == AppDomain.OPERATION) {

                updatedSchema.setRead(false);
            }

            if (PrincipalUtils.getDomainId() == AppDomain.CUSTOMER) {

                updatedSchema.setRead(true);
            }

            dao.update("CsrAskBoardSchemaMapper.updateById", updatedSchema);

            //保存操作日志
            Map<String, Object> dataBackup = new HashMap<>();
            dataBackup.put("ADD_CUSTOMERSERVICE_ASKBOARD_DETAIL", entry);
            PrincipalLogUtils.addOperationLog(ModuleNames.CSR, ModuleNames.CSR_ASK_BOARD, UserActions.ADD, "新增留言", dataBackup);

            resId = entry.getId();
        }

        CsrAskBoardDetail csrAskBoardDetail = (CsrAskBoardDetail)dao.findForObject(getSqlName("selectByPrimaryKey"), resId);

        CsrAskBoardDetailDto csrAskBoardDetailDto = new CsrAskBoardDetailDto();

        BeanUtils.copyProperties(csrAskBoardDetail, csrAskBoardDetailDto);

        return translateDetail2CsrAskBoardDetailDto(csrAskBoardDetailDto);
    }

    @Override
    public void batchDelete(List<Integer> ids) {
        if (ids != null && ids.size() > 0) {

            dao.update(getSqlName("logicDeleteByIds"), ids);
        }

        Map<String, Object> dataBackup = new HashMap<>();
        dataBackup.put("DELETE_CUSTOMERSERVICE_ASKBOARD_DETAIL", ids);
        PrincipalLogUtils.addOperationLog(ModuleNames.CSR, ModuleNames.CSR_ASK_BOARD, UserActions.DELETE, "删除留言", dataBackup);
    }

    @Override
    public QResultDto getHistoryList(int pageSize, int pageIndex, int refAskBoardId) {

        List<CsrAskBoardDetailDto> csrAskBoardDetailDtoList = new ArrayList<CsrAskBoardDetailDto>();

        QueryParams params = new QueryParams(pageSize, pageIndex, null, null, false, null);
        params.put("refAskBoardId", refAskBoardId);

        ParamData pd = this.convertQueryParams(params);

        List<CsrAskBoardDetail> csrAskBoardDetailList = dao.findForList(getSqlName("historyListPage"), pd, CsrAskBoardDetail.class);

        if (csrAskBoardDetailList != null && csrAskBoardDetailList.size() > 0) {

            for (int i = 0; i < csrAskBoardDetailList.size(); i++) {

                CsrAskBoardDetailDto csrAskBoardDetailDto = new CsrAskBoardDetailDto();

                BeanUtils.copyProperties(csrAskBoardDetailList.get(i), csrAskBoardDetailDto);

                CsrAskBoardDetailDto tempCsrAskBoardDetailDto = translateDetail2CsrAskBoardDetailDto(csrAskBoardDetailDto);

                csrAskBoardDetailDtoList.add(tempCsrAskBoardDetailDto);
            }
        }

        QResultDto qResultDto = new QResultDto();

        qResultDto.setPagination(pd.getPagination());
        qResultDto.setData(csrAskBoardDetailDtoList);

        return qResultDto;
    }

    @Override
    public CsrAskBoardDetailDto translateDetail2CsrAskBoardDetailDto(CsrAskBoardDetailDto csrAskBoardDetailDto) {

        if (csrAskBoardDetailDto.getIsModerator()) {

            CusUser cusUser = customerUserService.findById(csrAskBoardDetailDto.getRefReplyerId());

            if (cusUser != null) {

                csrAskBoardDetailDto.setRefReplyerFullName(cusUser.getFullName());
                csrAskBoardDetailDto.setGetRefReplyerUserName(cusUser.getUserName());

                List<FileInfoDto> attachments = fileGroupService.getFileDtosByGroupId(cusUser.getUserAvatar());

                if (attachments != null && attachments.size() > 0) {

                    csrAskBoardDetailDto.setAvatarFilePath(attachments.get(0).getPath());
                }
            }

        } else {

            UserDto userDto = userService.findUserDetailByUserId(csrAskBoardDetailDto.getRefReplyerId());

            if (userDto != null) {

                csrAskBoardDetailDto.setGetRefReplyerUserName(userDto.getUserName());
                csrAskBoardDetailDto.setRefReplyerFullName(userDto.getFullName());

                SysFile sysFile = sysFileService.getFileInfo(userDto.getAvatarId());

                if (sysFile != null) {

                    csrAskBoardDetailDto.setAvatarFilePath(sysFile.getFileLocation());
                }
            }

        }

        return csrAskBoardDetailDto;
    }

    private void checkDataValid(CsrAskBoardDetail csrAskBoardDetail) {

        if (csrAskBoardDetail.getRefAskBoardId() <= 0) {

            throw Exceptions.bizException(ErrorCodes.ERROR_ARGUMENT_EMPTY, "AskBoardId");
        }

        if (StringUtils.isEmpty(csrAskBoardDetail.getMessageBody())) {

            throw Exceptions.bizException(ErrorCodes.ERROR_LEAVE_MESSAGE_IS_NULL);
        }

    }

    @Override
    protected String getMapperNamespace() {
        return "CsrAskBoardDetailMapper";
    }
}
